package com.ecable.action;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.org.apache.commons.beanutils.BeanUtils;
import com.ecable.bean.VillageTO;
import com.ecable.delegate.VillageMgrDelegate;
import com.ecable.exception.ConnectionException;
import com.ecable.exception.LoginException;
import com.ecable.util.UtilConstants;

public class AddVillageAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -954350565195437778L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String path = "";
		RequestDispatcher rd = null;

		boolean flag = false;

		VillageTO vto = new VillageTO();

		Map map = request.getParameterMap();
		try {
			BeanUtils.populate(vto, map);
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();

		}

		try {

			VillageMgrDelegate vdelegate = new VillageMgrDelegate();

			try {

				flag = vdelegate.insertVillage(vto);
			}

			catch (ConnectionException ce) {
				throw new ServletException("server busy please try again");
			}

			catch (LoginException le) {
				request.setAttribute("status", UtilConstants._INVALID_USER);
				rd = request
						.getRequestDispatcher(UtilConstants._LOGIN_FAILED_PAGE);
			}

			if (flag) {

				request.setAttribute("status",
						UtilConstants._VILLAGE_INSERTED_SUCCESS);
				path = UtilConstants._VILLAGE_HOME;

			} else {

				request.setAttribute("status",
						UtilConstants._VILLAGE_INSERTED_FAIL);
				path = UtilConstants._VILLAGE_HOME;

			}

		} catch (ServletException e) {

			e.printStackTrace();
			path = UtilConstants._VILLAGE_HOME;
			request.setAttribute("status", UtilConstants._SERVER_BUSY);

		}

		rd = request.getRequestDispatcher(path);

		rd.forward(request, response);
	}

}
